package com.gitee.fsmxm.thinking.in.concurrent.basic;

import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.StampedLock;

// StampedLock不支持重入
public class _08_StampedLock {

    public static void main(String[] args) throws InterruptedException {

        //slSample();


        final StampedLock lock = new StampedLock();
        Thread T1 = new Thread(() -> {
            // 获取写锁
            lock.writeLock();
            // 永远阻塞在此处，不释放写锁
            LockSupport.park();
        });
        T1.start();
        // 保证T1获取写锁
        Thread.sleep(100);
        //阻塞在悲观读锁
        Thread T2 = new Thread(lock::readLock);
        T2.start();
        // 保证T2阻塞在读锁
        Thread.sleep(100);
        //中断线程T2
        //会导致线程T2所在CPU飙升
        T2.interrupt();
        T2.join();
    }

    private static void slSample() {
        final StampedLock sl = new StampedLock();

        // 获取/释放悲观读锁示意代码
        long stamp = sl.readLock();
        try {
            //省略业务相关代码
        } finally {
            sl.unlockRead(stamp);
        }

        // 获取/释放写锁示意代码
        stamp = sl.writeLock();
        try {
            //省略业务相关代码
        } finally {
            sl.unlockWrite(stamp);
        }
    }

}
